﻿using Microsoft.Win32;
using System;
using System.Linq;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Workbench.Operations;
using Workbench.Shared;

namespace Workbench.Presentation
{
    public partial class ApplicationMenuView : UserControl
    {
        public ApplicationMenuView()
        {
            InitializeComponent();

            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            debugProjectPath = Path.Combine(documentsPath, "Nora.wbdb");
            debugNoraPath = Path.Combine(documentsPath, "Nora Robyrts");
        }

        private void NewProject_Click(object sender, RoutedEventArgs e)
        {
            var fbd = new NewProjectDialog();
            var result = fbd.ShowDialog();
            if (result.HasValue && result.Value == true)
            {
                ViewModel.CreateProject(fbd.ViewModel.ProjectName, fbd.ViewModel.ProjectDbPath);
            }
        }

        private void OpenProject_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog()
            {
                Filter = "Workbench DB (*.wbdb)|*.wbdb",
                ValidateNames = true,
                InitialDirectory = UserSettings.LastUsedDirectory,
                CheckFileExists = true,
                CheckPathExists = true,
                Multiselect = false
            };

            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                UserSettings.LastUsedDirectory = Path.GetDirectoryName(dlg.FileName);
                ViewModel.OpenProject(dlg.FileName);
            }
        }

        private void CloseProject_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.CloseProject();
        }

        private string debugProjectPath;
        private string debugNoraPath;
        private void OpenDebugProject_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.OpenProject(debugProjectPath);
        }

        private void RecreateDebugProject_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.CloseProject();
            if (File.Exists(debugProjectPath))
            {
                while (true)
                {
                    try
                    {
                        File.Delete(debugProjectPath);
                        break;
                    }
                    catch
                    { }
                }
            }
            ViewModel.CreateProject("Nora", debugProjectPath);
            var rootDirectory = ProjectOperations.GetRootDirectory();
            var ptvm = new ProjectTreeViewModel();
            ptvm.AddExistingDirectory(debugNoraPath, new ProjectDirectoryViewModel(rootDirectory));
            AddDefaultPOSTypes();
        }

        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void ApplicationMenu_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ViewModel = e.NewValue as ApplicationMenuViewModel;
        }

        public ApplicationMenuViewModel ViewModel { get; private set; }

        public static void AddDefaultPOSTypes()
        {
            ProjectOperations.AddPOSType("Noun", null);
            ProjectOperations.AddPOSType("Verb", null);
            ProjectOperations.AddPOSType("Adjective", null);
            ProjectOperations.AddPOSType("Adverb", null);
            ProjectOperations.AddPOSType("Determiner", null);
            ProjectOperations.AddPOSType("Conjunction", null);
            ProjectOperations.AddPOSType("Preposition", null);
            ProjectOperations.AddPOSType("Interjection", null);
            ProjectOperations.AddPOSType("Particle", null);
            ProjectOperations.AddPOSType("Pronoun", null);
            ProjectOperations.AddPOSType("Numerical", null);
        }

        private void RecentProject_Click(object sender, RoutedEventArgs e)
        {
            var originalSender = e.OriginalSource as MenuItem;
            var projectDbPath = originalSender.Header as string;
            try
            {
                ViewModel.OpenProject(projectDbPath);
            }
            catch (IOException)
            {
                var result = MessageBox.Show("The project appears to have been deleted. Do you want to remove it from the recently used list?", "Missing project", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No, MessageBoxOptions.None);
                if(result == MessageBoxResult.Yes)
                {
                    ViewModel.RemoveFromRecentlyUsed(projectDbPath);
                }
            }
        }

        private void DeployPOSTypes_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("This action will delete all you existing POS types and all tagged words will be cleared. Are you sure you want to continue?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);

            if (result == MessageBoxResult.Yes)
            {
                var mi = e.OriginalSource as MenuItem;
                try
                {
                    ViewModel.ImportPOSTypesSet(mi.Header as string);
                    var posTypes = ProjectOperations.GetPOSTypes().Select(x => new POSTypeViewModel(x));
                    StateContanainer.Current.POSTypes.Clear();
                    StateContanainer.Current.POSTypes.AddRange(posTypes);
                }
                catch (Exception ex)
                {
                    LoggingService.LogError(ex);
                }
            }
        }   
    }
}
